<template>
  <div class="vacation-rules-container">
    <div class="page-header">
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        新增班次
      </el-button>
    </div>

    <el-table v-loading="loading" :data="shiftList" border style="width: 100%">
      <el-table-column prop="name" label="班次名称" min-width="120" />
      <el-table-column label="班次时间" min-width="120">
        <template #default="{ row }"> {{ row.timess }} </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleEdit(row)"> 查看 </el-button>
          <el-button type="danger" link @click="handleDelete(row)"> 删除 </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增/编辑抽屉 -->
    <el-drawer
      v-model="drawerVisible"
      v-if="drawerVisible"
      :title="isEdit ? '编辑班次' : '新增班次'"
      size="500px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      direction="rtl"
      class="vacation-drawer"
     >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="90px"
        class="drawer-form"
      >
        <div class="section-title">
          <el-form-item label="班次名称" prop="name">
            <el-input  :disabled="flackss" v-model="formData.name" placeholder="请输入" />
          </el-form-item>
        </div>
        <!-- <div style="margin-bottom: 12px; transform: translateX(20px)" v-if="!kuabanone">
          上下班时间
          <span style="color: blue; cursor: pointer" @click="banciadds">{{
            !bancitow ? "添加" : "减少"
          }}</span>
        </div> -->
        <div
          style="margin-bottom: 12px; transform: translateX(20px); height: 21px"
          v-if="kuabanone"
         ></div>
        <div class="form-section">
          <div class="section-title" style="font-weight: 600">第1次上下班</div>
          <el-form-item label="上班时间" prop="onDutyTime">
            <el-time-select
             :disabled="flackss"
              v-model="formData.onDutyTime"
              style="width: 50%"
              class="mr-4"
              format="HH:mm"
              placeholder="Start time"
              start="00:00"
              step="00:10"
              end="23:50"
            />
          </el-form-item>
          <el-form-item label="下班时间" prop="offDutyTime">
            <el-time-select
            :disabled="flackss"
              v-model="formData.offDutyTime"
              style="width: 50%"
              class="mr-4"
              format="HH:mm"
              placeholder="End time"
              start="00:00"
              step="00:10"
              end="23:50"
            />
            <!-- <span class="kuaban" v-if="kuabanone">次日</span>
            <div style="width: 50%; display: flex; justify-content: flex-end">
              <el-checkbox
                v-if="!bancitow"
                v-model="kuabanone"
                label="跨天"
                size="large"
              />
            </div> -->
          </el-form-item>
        </div>

        <!-- <div class="form-section" v-if="bancitow">
          <div class="section-title" style="font-weight: 600">第2次上下班</div>
          <el-form-item label="上班时间" prop="onDutyTime2">
            <el-time-select
              v-model="formData.onDutyTime2"
              style="width: 50%"
              class="mr-4"
              format="HH:mm"
              placeholder="Start time"
              start="00:00"
              step="00:10"
              end="23:50"
            />
          </el-form-item>
          <el-form-item label="下班时间" prop="offDutyTime2">
            <el-time-select
              v-model="formData.offDutyTime2"
              style="width: 50%"
              class="mr-4"
              format="HH:mm"
              placeholder="Start time"
              start="00:00"
              step="00:10"
              end="23:50"
            />
            <span class="kuaban" v-if="kuabanone2">次日</span>
            <div style="width: 50%; display: flex; justify-content: flex-end">
              <el-checkbox v-model="kuabanone2" label="跨天" size="large" />
            </div>
          </el-form-item>
        </div> -->
      </el-form>

      <template #footer>
        <div class="drawer-footer">
          <el-button @click="handlecancel">取消</el-button>
          <el-button type="primary" @click="handleSubmit">保存</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from "vue";
import type { FormInstance } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import type { VacationRule } from "@/api/types/vacation";
import { getAttendanceGroupInfo } from "@/api/attendanceGroup";
import { delShiftInfo, addShiftInfo, updateShiftInfo, getShiftInfo } from "@/api/shift";

const kuabanone = ref(false);
// const kuabanone2 = ref(false);

// const bancitow = ref(false);

const banciadds = () => {
  if (formDataqw.sections.length > 1) {
    formDataqw.sections.splice(1, 1);
  }

  formData.onDutyTime2 = "";
  formData.offDutyTime2 = "";
  // kuabanone2.value = false;
  // bancitow.value = !bancitow.value;
};

// // 获取今天的日期并设置为当天的00:00:00
const today = new Date();
today.setHours(0, 0, 0, 0);
console.log(today);

const shiftList = ref(<Array<unknown> | any>[]);
const loading = ref(<Boolean>true);
// 抽屉相关
const drawerVisible = ref(false);
const isEdit = ref(false);
const formRef = ref<FormInstance>();

const formData = reactive({
  name: "",
  onDutyTime: "",
  offDutyTime: "",
  // onDutyTime2: "",
  // offDutyTime2: "",
});

const formDataqw = reactive({
  name: "shift_name",
  sections: [
    {
      times: [
        {
          across: 0,
          check_type: "OnDuty",
          free_check: false,
          check_time: "on_duty_time",
        },
        {
          across: 0,
          check_type: "OffDuty",
          free_check: false,
          check_time: "off_duty_time",
        },
      ],
    },
  ],
});

// const formDataas = reactive({
//   times: [
//     {
//       across: 0,
//       check_type: "OnDuty",
//       free_check: false,
//       check_time: "2020-12-02 19:00:00",
//     },
//     {
//       across: 0,
//       check_type: "OffDuty",
//       free_check: false,
//       check_time: "2020-12-02 20:00:00",
//     },
//   ],
// });

// 取消按钮
const handlecancel = () => {
  drawerVisible.value = false;
  kuabanone.value = false;
  // kuabanone2.value = false;
  // bancitow.value = false;
  Object.assign(formData, {
    name: "",
    onDutyTime: "",
    offDutyTime: "",
    // onDutyTime2: "",
    // offDutyTime2: "",
  });
};

// formData.offDutyTime = ref(today);

// 表单校验规则
const rules = {
  name: [{ required: true, message: "请输入班次名称", trigger: "blur" }, { min: 1 }],
  onDutyTime: [{ required: true, message: "请选择上班时间", trigger: "change" }],
  offDutyTime: [{ required: true, message: "请选择下班时间", trigger: "change" }],
  // onDutyTime2: [{ required: true, message: "请选择上班时间", trigger: "change" }],
  // offDutyTime2: [{ required: true, message: "请选择下班时间", trigger: "change" }],
};

// 新增
const handleAdd = () => {
  flackss.value=false
  kuabanone.value = false;
  // kuabanone2.value = false;
  // bancitow.value = false;

  // if (formDataqw.sections.length > 1) {
  //   formDataqw.sections.splice(1, 1);
  // }

  isEdit.value = false;
  Object.assign(formData, {
    name: "",
    onDutyTime: "",
    offDutyTime: "",
    // onDutyTime2: "",
    // offDutyTime2: "",
  });
  drawerVisible.value = true;
};

const flackss=ref(false)
// 编辑
const handleEdit = (row: any) => {
  flackss.value=true
  console.log(row);

  isEdit.value = true;

  const trrdata = row.timess.split("-");

  // // 多班次的时间回显处理
  // if (trrdata.length > 2) {
  //   if (row.sections[1].times[1].across == "1") {
  //     kuabanone2.value = true;
  //   } else {
  //     kuabanone2.value = false;
  //   }

  //   console.log(trrdata);
  //   // 分割第二个时间

  //   const strshijan1 = trrdata[1].split("&");
  //   console.log(strshijan1);
  //   Object.assign(formData, {
  //     id: row.id,
  //     name: row.name,
  //     onDutyTime: trrdata[0],
  //     offDutyTime: strshijan1[0],
  //     onDutyTime2: strshijan1[1],
  //     offDutyTime2: trrdata[2],
  //   });

  //   bancitow.value = true;
  // } else {
    // 单班次的时间处理
    if (row.sections[0].times[1].across == "1") {
      kuabanone.value = true;
    } else {
      kuabanone.value = false;
    }
    Object.assign(formData, {
      id: row.id,
      name: row.name,
      onDutyTime: trrdata[0],
      offDutyTime: trrdata[1],
    });
  // }

  drawerVisible.value = true;
};

// 删除
const handleDelete = (row: VacationRule) => {
  ElMessageBox.confirm("确定要删除该班次吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      if (row) {
        console.log(row);
        const res = await delShiftInfo(row.id);
        if (res.code == 200) {
          ElMessage.success("删除成功");
          getData();
        } else {
          ElMessage.error("删除失败");
        }
      }
    })
    .catch(() => {});
};

// 验证时间大小
const yanzhanegshijian = (valone: any, valtoe: any) => {
  const strq = valone + " ";
  const arrq = strq.split(":");
  const str1q = valtoe + " ";
  const arr1q = str1q.split(":");
  if (arrq[0] > arr1q[0]) {
    return true;
  } else if (arrq[0] == arr1q[0]) {
    if (arrq[1] >= arr1q[1]) {
      return true;
    }
  }
  return false;
};

// 提交表单
const handleSubmit = async () => {
  // console.log(bancitow.value);
  console.log(kuabanone.value);

  if (!formRef.value) return;
  try {
    await formRef.value.validate();

    if (yanzhanegshijian(formData.onDutyTime, formData.offDutyTime)) {
          ElMessage.error("下班时间不能比上班时间早");
          return;
        }

    // // 班次时间规则的校验
    // if (bancitow.value) {
    //   if (yanzhanegshijian(formData.offDutyTime, formData.onDutyTime2)) {
    //     ElMessage.error("第一次的下班时间不能比第二次上班时间早");
    //     return;
    //   }
    //   if (!kuabanone2.value) {
    //     if (
    //       yanzhanegshijian(formData.onDutyTime, formData.offDutyTime) ||
    //       yanzhanegshijian(formData.onDutyTime2, formData.offDutyTime2)
    //     ) {
    //       ElMessage.error("两个班次的下班时间都不能比上班时间早");
    //       return;
    //     }
    //     if (yanzhanegshijian(formData.offDutyTime, formData.onDutyTime2)) {
    //       ElMessage.error("第一次的下班时间不能比第二次上班时间早");
    //       return;
    //     }
    //   } else {
    //     if (yanzhanegshijian(formData.onDutyTime, formData.offDutyTime)) {
    //       ElMessage.error("第一次上下班的下班时间不能比上班时间早");
    //       return;
    //     }
    //   }
    // } else {
    //   if (!kuabanone.value) {
    //     if (yanzhanegshijian(formData.onDutyTime, formData.offDutyTime)) {
    //       ElMessage.error("下班时间不能比上班时间早");
    //       return;
    //     }
    //   }
    // }

    if (isEdit.value) {
      formDataqw.id = formData.id;
      formDataqw.name = formData.name;
      formDataqw.sections[0].times[0].check_time = `2020-12-02 ${formData.onDutyTime}:00`;
      formDataqw.sections[0].times[1].check_time = `2020-12-02 ${formData.offDutyTime}:00`;

      if (kuabanone.value) {
        formDataqw.sections[0].times[1].across = 1;
      } else {
        formDataqw.sections[0].times[1].across = 0;
      }

      // if (kuabanone2.value) {
      //   formDataas.times[1].across = 1;
      // } else {
      //   formDataas.times[1].across = 0;
      // }
      // if (bancitow.value) {
      //   formDataas.times[0].check_time = `2020-12-12 ${formData.onDutyTime2}:00`;
      //   formDataas.times[1].check_time = `2020-12-02 ${formData.offDutyTime2}:00`;
      // }
      // if (bancitow.value) {
      //   if (formDataqw.sections.length < 2) {
      //     formDataqw.sections.push(formDataas);
      //   }
      // } else {
      //   formDataqw.sections.splice(1, 1);
      // }

      const res = await updateShiftInfo(formDataqw);

      if (res.code == "200") {
        ElMessage.success("修改成功");
      } else {
        ElMessage.error("修改失败");
      }

      getData();
    } else {
      formDataqw.name = formData.name;
      formDataqw.sections[0].times[0].check_time = `2020-12-02 ${formData.onDutyTime}:00`;
      formDataqw.sections[0].times[1].check_time = `2020-12-02 ${formData.offDutyTime}:00`;

      if (kuabanone.value) {
        formDataqw.sections[0].times[1].across = 1;
      } else {
        formDataqw.sections[0].times[1].across = 0;
      }

      // if (kuabanone2.value) {
      //   formDataas.times[1].across = 1;
      // } else {
      //   formDataas.times[1].across = 0;
      // }
      // if (bancitow.value) {
      //   formDataas.times[0].check_time = `2020-12-02 ${formData.onDutyTime2}:00`;
      //   formDataas.times[1].check_time = `2020-12-02 ${formData.offDutyTime2}:00`;
      // }
      // if (bancitow.value) {
      //   if (formDataqw.sections.length < 2) {
      //     formDataqw.sections.push(formDataas);
      //   }
      // } else {
      //   formDataqw.sections.splice(1, 1);
      // }

      const res = await addShiftInfo(formDataqw);
      if (res.code == 200) {
        ElMessage.success("新增成功");
        getData();
      } else {
        ElMessage.error("添加失败");
        kuabanone.value = false;
        // kuabanone2.value = false;
        // bancitow.value = false;
      }
    }
    drawerVisible.value = false;
  } catch (error) {
    console.error("表单验证失败:", error);
  }
};

//初始化获取数据
const getData = async () => {
  const res = await getShiftInfo();

  res.data.forEach((item: any) => {
    
    // const trrshijian: any = [];
    // if (item.sections.length > 1) {
    //   item.sections.forEach((vak: any) => {
    //     const str = vak.times[0].check_time.toString().split(" ")[1];
    //     const dateval = `${str.split(":")[0]}:${str.split(":")[1]}`;
    //     const str1 = vak.times[1].check_time.toString().split(" ")[1];
    //     const dateval1 = `${str1.split(":")[0]}:${str1.split(":")[1]}`;
    //     trrshijian.push(`${dateval}-${dateval1}`);
    //   });
    //   item.timess = `${trrshijian[0]} & ${trrshijian[1]}`;
    // } else {
      const str = item.sections[0].times[0].check_time.toString().split(" ")[1];
      const dateval = `${str.split(":")[0]}:${str.split(":")[1]}`;
      const str1 = item.sections[0].times[1].check_time.toString().split(" ")[1];
      const dateval1 = `${str1.split(":")[0]}:${str1.split(":")[1]}`;
      item.timess = `${dateval}-${dateval1}`;
    // }
  });

  loading.value = false;
  shiftList.value = res.data;
};
// 初始化数据
onMounted(() => {
  getData();
});
</script>

<style lang="scss" scoped>
.kuaban {
  position: absolute;
  top: 8px;
  left: 52%;
  border-radius: 8px;
  background-color: #fff0f0;
  border: 1px solid red;
  color: red;
  display: inline-block;
  width: 40px;
  text-align: center;
  line-height: 24px;
  height: 25px;
}

element.style {
  text-align: center;
}
.vacation-rules-container {
  padding: 20px;
  background: #fff;
  border-radius: 4px;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    h2 {
      margin: 0;
      font-size: 18px;
      font-weight: 600;
    }
  }

  :deep(.el-button) {
    .el-icon {
      margin-right: 4px;
    }
  }
}

.form-section {
  margin-bottom: 24px;
  padding: 16px;
  background-color: #f5f7fa;
  border-radius: 4px;

  .section-title {
    font-size: 14px;
    font-weight: 500;
    color: #303133;
    margin-bottom: 16px;
  }

  .section-tip {
    font-size: 12px;
    color: #909399;
    margin: -8px 0 16px 120px;
  }

  :deep(.el-form-item:last-child) {
    margin-bottom: 0;
  }
}

.drawer-form {
  padding: 20px;

  :deep(.el-form-item) {
    margin-bottom: 22px;
  }
}

.drawer-footer {
  position: absolute;
  right: 0;
  bottom: 0;
  left: 0;
  padding: 16px 20px;
  background: #fff;
  border-top: 1px solid #dcdfe6;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

// 修改抽屉自定义样式
.vacation-drawer {
  :deep(.el-drawer__header) {
    margin: 0;
    padding: 16px 20px;
    border-bottom: 1px solid #dcdfe6;

    .el-drawer__title {
      font-size: 16px;
      font-weight: 500;
      color: #303133;
    }

    .el-drawer__close-btn {
      margin-right: -6px;
    }
  }

  :deep(.el-drawer__body) {
    padding: 0;
  }
}
:deep(.el-drawer__body) {
  padding-top: 0 !important;
}

:deep(.el-drawer__header) {
  margin-bottom: 0 !important;
  padding-top: 16px !important;
  padding-bottom: 16px !important;
}
</style>
